﻿using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

namespace MockingBird.Wsdl.Parser
{

    /// <summary>
    /// Represents an endpoint
    /// </summary>
    public class Endpoint
    {
        #region "private members"
        private XElement endpointElement;
        #endregion

        #region "public properties"
        public string Name { get; private set; }
        public string BindingName { get; private set; }
        public string Address { get; private set; }
        #endregion

        public Endpoint(XElement svcEndpointElement)
        {
            this.endpointElement = svcEndpointElement;
        }



        public void Fill()
        {
            //Get the name of the port/endpoint - Acquire the Name attribute
            this.Name = GetAttributeName("//*[local-name()='port']/@*[local-name()='name']");
            this.BindingName = GetAttributeName("//*[local-name()='port']/@*[local-name()='binding']");

            //if it is a qualified name, drop the namespace part 
            if (this.BindingName.Contains(":"))
                BindingName = BindingName.Substring(BindingName.IndexOf(":") + 1);

            this.Address = GetAttributeName("//*[local-name()='port']/*[local-name()='address']/@*[local-name()='location']");


        }
        private string GetAttributeName(string xpathExpression)
        {
            System.Collections.IEnumerable att = (System.Collections.IEnumerable)endpointElement.XPathEvaluate(xpathExpression);
            XAttribute xatt = att.Cast<XAttribute>().FirstOrDefault();
            return xatt.Value;
        }
    }
}
